package com.concerneyes;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.concerneyes.CEApp;
import com.concerneyes.MainActivity;
import com.concerneyes.R;
import com.concerneyes.task.DeviceInfo;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import common.AbsActivity;
import common.AbsBaseView;
import common.PreferUtil;
import http.JsonMap;
import http.LoginTask;
import util.CodeUtils;


/**
 * Depiction: 登录界面
 * <p>
 * Modify:
 * <p>
 * Author: Kevin Lynn
 * <p>
 * Create Date：2016年1月25日 下午2:33:17
 * <p>
 *
 * @version 1.0
 * @since 1.0
 */
public class LoginActivity extends AbsActivity implements OnClickListener {
    private static final String TAG = "LoginView";
    private static final String PHONE = "0";
    private static final String WECHAT = "1";
    private static final String QQ = "2";
    private Button loginBtn;

    private EditText phoneInput;
    private EditText passwdInput;
    private EditText sms_code;
    private ImageView iv_code;
    private TextView tv_change;
    private TextView get_code;
    private LinearLayout qqLog, weChatLog;

    private CodeUtils codeUtils;

    public BaseUiListener getmIUiListener() {
        return new BaseUiListener();
    }

    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;
    private Tencent mTencent;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.view_login);
        initView();
    }

    private void initView() {
        // 传入参数APPID和全局Context上下文
        mTencent = Tencent.createInstance(CEApp.APP_ID, this);
        phoneInput = (EditText) findViewById(R.id.phone_input);
        passwdInput = (EditText) findViewById(R.id.passwd_input);
        sms_code = (EditText) findViewById(R.id.sms_code);
        get_code = (TextView) findViewById(R.id.get_code);
        get_code.setOnClickListener(this);
        phoneInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextIsNull();
            }
        });
        passwdInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextIsNull();
            }
        });
        sms_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextIsNull();
            }
        });
        iv_code = (ImageView) findViewById(R.id.iv_code);
        tv_change = (TextView) findViewById(R.id.tv_change);
        loginBtn = (Button) findViewById(R.id.login_btn);

        qqLog = (LinearLayout) findViewById(R.id.qq_log);
        weChatLog = (LinearLayout) findViewById(R.id.wechat_log);
        qqLog.setOnClickListener(this);
        weChatLog.setOnClickListener(this);
        tv_change.setOnClickListener(this);

        codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
        iv_code.setImageBitmap(bitmap);
    }


    private void editTextIsNull() {
        String phone = phoneInput.getText().toString().trim();
        String codeStr = passwdInput.getText().toString().trim();
        String sms = sms_code.getText().toString().trim();
        if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(codeStr) && !TextUtils.isEmpty(sms)) {
            loginBtn.setBackground(getResources().getDrawable(R.drawable.btn_blue_bg));
            loginBtn.setOnClickListener(this);
        } else {
            loginBtn.setBackground(getResources().getDrawable(R.drawable.btn_unclick_blue_bg));
        }
    }


    @Override
    public void onClick(View v) {
        String phone = phoneInput.getText().toString().trim();
        String codeStr = passwdInput.getText().toString().trim();
        String sms = sms_code.getText().toString().trim();
        switch (v.getId()) {
            case R.id.login_btn:
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入手机号码", 0).show();
                    return;
                }
                if (null == codeStr || TextUtils.isEmpty(codeStr)) {
                    Toast.makeText(this, "请输入验证码", 0).show();
                    return;
                }
                String code = codeUtils.getCode();
                if (code.equalsIgnoreCase(codeStr)) {
                    Toast.makeText(this, "验证码正确", 0).show();
                } else {
                    Toast.makeText(this, "验证码错误", 0).show();
                    return;
                }
                if (TextUtils.isEmpty(sms)) {
                    Toast.makeText(this, "请输入短信验证码", 0).show();
                    return;
                }
                break;
            case R.id.get_code:
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入手机号码", 0).show();
                    return;
                }
                getCodeTimer();
                break;
            case R.id.qq_log:
                /**
                 * 通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO
                 * 是一个String类型的字符串，表示一些权限 官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE =
                 * “get_user_info,add_t”；所有权限用“all”
                 * 第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类
                 */
//                // all表示获取所有权限
                mIUiListener = new BaseUiListener();
                mTencent.login(LoginActivity.this, "all", mIUiListener);
                //TODO shareSDK QQ三方登录存在回调问题
//                Platform qq = ShareSDK.getPlatform(QQ.NAME);
//                qq.SSOSetting(false);  //设置false表示使用SSO授权方式
//                qq.setPlatformActionListener(this); // 设置分享事件回调
//                qq.authorize();//单独授权
//                qq.showUser(null);//授权并获取用户信息
                break;
            case R.id.wechat_log:
                onWebchatLogin();
                break;
            case R.id.tv_change:
                codeUtils = CodeUtils.getInstance();
                Bitmap bitmap = codeUtils.createBitmap();
                iv_code.setImageBitmap(bitmap);
                break;
            default:
                break;
        }
    }

    public void onWebchatLogin() {
        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
        platform.SSOSetting(false);  //设置false表示使用SSO授权方式
        Toast.makeText(LoginActivity.this, "授权", Toast.LENGTH_SHORT).show();
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, final HashMap<String, Object> hashMap) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "授权成功~~", Toast.LENGTH_SHORT).show();
                        Log.e(this.getClass().getSimpleName(), "onComplete()-->" + hashMap.toString());
                        String openid = hashMap.get("openid").toString();
                        String unionid = hashMap.get("unionid").toString();
                        String nickname = hashMap.get("nickname").toString();
                        String gender = "";
                        if (hashMap.get("sex").toString().equals("0")) {
                            gender = LoginActivity.this.getResources().getString(R.string.man_);
                        } else {
                            gender = LoginActivity.this.getResources().getString(R.string.woman_);
                        }
                        String portrait = hashMap.get("headimgurl").toString();
                        login(WECHAT, gender, nickname, openid, portrait, unionid);
                    }
                });
            }

            @Override
            public void onError(Platform platform, int i, final Throwable throwable) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                        Log.e(this.getClass().getSimpleName(), "onError()-->" + throwable.toString());
                    }
                });

            }

            @Override
            public void onCancel(Platform platform, int i) {
                Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
                Log.d(this.getClass().getSimpleName(), "onCancel()-->" + platform.toString());
            }
        }); // 设置分享事件回调
//        platform.authorize();//单独授权
        if (platform.isAuthValid()){
            platform.removeAccount(true);
        }
        platform.showUser(null);//授权并获取用户信息
    }

    //=================================QQ/微信登录功能=============================================

    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法 onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(final Object response) {
            // loadData(response);
            Toast.makeText(LoginActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
            JSONObject obj = (JSONObject) response;
            Log.e(this.getClass().getSimpleName(), "responseqq==>" + response.toString());

            try {
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken, expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new UserInfo(LoginActivity.this, qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response_login) {
                        JsonMap map = JsonMap.parseJson(response.toString());
                        JsonMap loginMap = JsonMap.parseJson(response_login.toString());
                        Log.e(TAG, "response_login==>" + response_login);
                        String gender = loginMap.getString("gender");
                        String nickname = loginMap.getString("nickname");
                        String openid = map.getString("openid");
                        String access_token = map.getString("access_token");
                        String portrait = loginMap.getString("figureurl_qq_2");
                        login(QQ, gender, nickname, openid, portrait, null);
                    }

                    @Override
                    public void onError(UiError uiError) {
                    }

                    @Override
                    public void onCancel() {

                    }

                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();

        }

    }

    /**
     * 获取验证码按钮倒计时
     */
    private void getCodeTimer() {
        post(new Runnable() {
            @Override
            public void run() {
                new CountDownTimer(60000, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                        get_code.setEnabled(false);
                        get_code.setBackgroundResource(R.drawable.btn_light_gray_bg);
                        get_code.setText(getResources().getString(R.string.code_down_time, millisUntilFinished / 1000));
                        get_code.setTextColor(getResources().getColor(R.color.app_blue));
                    }

                    @Override
                    public void onFinish() {
                        get_code.setText(R.string.reget_code);
                        get_code.setBackgroundResource(R.drawable.btn_blue_bg);
                        get_code.setTextColor(getResources().getColor(R.color.white));
                        get_code.setEnabled(true);
                    }
                }.start();
            }
        });
    }

    public void login(String userType, String gender, String nickname, String openid, String portrait, String unionid) {
        LoginTask task = new LoginTask(userType, gender, nickname, openid, portrait, unionid) {
            @Override
            public void onPreExecute() {
                showLoadingDialog(R.string.login_ing);
            }

            @Override
            public void onPostExecute(boolean isSuccess, Object result) {
                if (!isSuccess) {
                    cancelLoadingDialog();
                    return;
                }
                Log.e(this.getClass().getSimpleName(), "onPostExecute1111111");
                new DeviceInfo();
//                JPushInterface.setAlias();设置别名
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        };
        task.excute();
    }

    /**
     * 在调用Login的Activity或者Fragment中重写onActivityResult方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, getmIUiListener());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
